#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import json
import datetime
import time
import logging
import sys
import os
import subprocess
import pymysql

from sanic import Sanic, response
import uvloop
import asyncio
import mysqlconn
import opsjwt
import hashlib

# pip3 install Sanic

def getmenu(request):
  print("getmenu:")
  workcode=datetime.datetime.now().strftime("%Y%m%d%H%M%S.%f")
  try:
    #第一步：打开数据库连接
    db = pymysql.connect(host="192.168.1.233",
                  user="admin",
                  password="Boluome_mysql888",
                  port=3306,# 端口
                  database="order_report",
                  charset='utf8')

    sql="select a.menuname ,a.uid ,(select CONCAT('[',GROUP_CONCAT(JSON_OBJECT('label',b.menuname,'value',b.uid)),']')  as childnode from t_sysmenu b where b.isdel=0 and b.`status`=0 and b.parentmenu=a.uid) as children from t_sysmenu a where a.isdel=0 and a.`status`=0 and a.parentmenu=0;"



    mysqlcursor1 = db.cursor()
    mysqlcursor1.execute(sql)
    # 获取所有记录列表
    results = mysqlcursor1.fetchall()
    print("results:",results)

    list_menu=[]

    for row in results:
      print("row:",row)
      dict_menu={}
      dict_menu["label"] = row[0]
      dict_menu["value"] = row[1]
      if (row[2]!=None):
        dict_menu["children"] = json.loads(row[2])

      print("dict_menu:",str(dict_menu))
      list_menu.append(dict_menu)
      print("list_menu:",str(list_menu))

    # 提交到数据库执行
    db.commit()
    # 关闭mysql游标和连接
    mysqlcursor1.close()

    return response.json(list_menu)
  except  Exception as err:
    loginfo='workcode:【'+workcode+'】,【---执行数据库异常---】,异常信息为:【'+str(err)+'】'
    #若异常返回
    print('error',loginfo)
ckk = getmenu(request='test')
async def login(request):

  dict_rr={}
  workcode=datetime.datetime.now().strftime("%Y%m%d%H%M%S.%f")


  print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),workcode,"收到接口请求[/login]:")
  try:
    requestbody=request.json
    username=str(requestbody["name"])
    ip=request.socket[0]
    password=hashlib.md5(str(requestbody["password"]).encode(encoding='UTF-8')).hexdigest()
    print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),workcode,requestbody)
    print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),workcode,"执行数据库查询")
    mysql = mysqlconn.MyPymysqlPool("reportmysql")
    print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),workcode,"生成mysql对象")

    sqlone = "select aa.uid as userid,aa.username,aa.realname,aa.userstatus,GROUP_CONCAT(bb.menuurl) as menucode from (select a.uid,a.username,a.realname,GROUP_CONCAT(b.sysmenulist) as sysmenulist,a.userstatus from t_user a LEFT JOIN t_user_role b on CONCAT(',',a.roleidlist,',') like CONCAT('%,',b.uid,',%') and b.isdel=0 where a.isdel=0 and a.username='"+username+"' and a.userpwd='"+password+"')aa left join t_sysmenu bb on CONCAT(',',aa.sysmenulist,',') like CONCAT('%,',bb.uid,',%') and bb.isdel=0;"
    # paramsql=(username,password)
    result = mysql.getOne(sqlone)
    print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),workcode,"结束数据库查询")
    dict_userinfo={}

    if(result["userid"]!=None):


      dict_userinfo["userid"]=result["userid"]
      dict_userinfo["username"]=str(result["username"], encoding='utf-8')
      dict_userinfo["realname"]=str(result["realname"], encoding='utf-8')
      dict_userinfo["userstatus"]=result["userstatus"]
      dict_userinfo["menucode"]=str(result["menucode"], encoding='utf-8')

      token=opsjwt.generate_jwt_token(dict_userinfo["userid"],dict_userinfo["username"],dict_userinfo["realname"],dict_userinfo["userstatus"],dict_userinfo["menucode"])



      print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),workcode,"token:",token)


      dict_rr["code"]=0
      dict_rr["success"]="true"
      dict_rr["message"]="登录成功！"
      dict_rr["token"]=token

      #记录业务日志
      logtime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
      # insertlog(workcode,dict_userinfo["userid"],"loginlog",logtime,"登录系统成功",ip)

      #更新最近一次登录日志
      sqlone="update t_user set endlogintime=%s where uid=%s;"
      paramsql=(logtime,dict_userinfo["userid"])
      mysql.update(sqlone,paramsql)

      mysql.dispose()

    else:
      dict_rr["code"]=403
      dict_rr["success"]="false"
      dict_rr["message"]="登录失败，请检查您的用户名或密码"


    dict_rr["userinfo"]=dict_userinfo


  except  Exception as err:
    loginfo='workcode:【'+workcode+'】,【---执行数据库异常---】,异常信息为:【'+str(err)+'】'
    #若异常返回
    print('error',loginfo)
    dict_rr["code"]=500
    dict_rr["success"]="false"
    dict_rr["message"]="登录失败，请检查您的用户名或密码"


  return response.json(dict_rr)


